package com.galudisu.client

import java.util.concurrent.atomic.AtomicInteger

import akka.actor.{ActorPath, ActorSystem}
import akka.cluster.client.{ClusterClient, ClusterClientSettings}
import com.galudisu.comm.LogarithmCalcJob
import com.typesafe.config.ConfigFactory

import scala.concurrent.duration._
import scala.language.postfixOps

/**
  * @author galudisu
  */
object SimpleClusterClient extends App {

  // 加载服务端节点
  val config = ConfigFactory.load("client")
  val system = ActorSystem.create("ClusterSystem", config)

  val initialContacts = Set(
    ActorPath.fromString("akka.tcp://ClusterSystem@127.0.0.1:2551/system/receptionist"),
    ActorPath.fromString("akka.tcp://ClusterSystem@127.0.0.1:2552/system/receptionist"))

  // 创建该节点的接待员
  val c = system.actorOf(ClusterClient.props(ClusterClientSettings(system).withInitialContacts(initialContacts)),
    "client")

  // 定时发送信息
  val counter = new AtomicInteger

  import system.dispatcher

  system.scheduler.schedule(2.seconds, 2.seconds) {
    // 匹配多个节点情况下，消息随机传递给一个destination
    c ! ClusterClient.Send("/user/server", LogarithmCalcJob(30), localAffinity = true)
    // 消息传递到所有匹配的节点
    c ! ClusterClient.SendToAll("/user/server", LogarithmCalcJob(60))

    // 客户端发布消息到所有节点(不管是否匹配)
    c ! ClusterClient.Publish
  }
}